package com.dctp.common.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class UserRoleChainService {
    public static class UserRoleChain {
        public Long bottomRoleUserId;
        public Long middleRoleUserId;
        public Long topRoleUserId;
    }

    /**
     * 沿parent_id向上查找第一个bottom、middle、top角色用户id
     * @param parentId 上级用户id
     * @return UserRoleChain
     */
    public static UserRoleChain findRoleChain(Long parentId) {
        UserRoleChain chain = new UserRoleChain();
        Long currentId = parentId;
        while (currentId != null && currentId != 0) {
            Record user = Db.findFirst("SELECT id, parent_id, role_id FROM dctp_user WHERE id = ?", currentId);
            if (user == null) break;
            int roleId = user.getInt("role_id");
            if (chain.bottomRoleUserId == null && roleId == 2) {
                chain.bottomRoleUserId = user.getLong("id");
            }
            if (chain.middleRoleUserId == null && roleId == 3) {
                chain.middleRoleUserId = user.getLong("id");
            }
            if (chain.topRoleUserId == null && roleId == 4) {
                chain.topRoleUserId = user.getLong("id");
            }
            if (chain.bottomRoleUserId != null && chain.middleRoleUserId != null && chain.topRoleUserId != null) break;
            currentId = user.getLong("parent_id");
        }
        return chain;
    }
}
